//
//  SuppHallViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/15.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "SuppHallViewController.h"
#import "HallModel.h"
#import "CloseGoodsAddressViewController.h"
#import "HallScreeningViewController.h"
#import "ReleaseHallViewController.h"
#import "DeliveryDetailsViewController.h"

static NSString *cellPath = @"SuppHallCell";
@interface SuppHallViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *screeView;
    UILabel *startLab;
    UILabel *stopLab;
}
@property (nonatomic, strong)NSMutableArray *allHallAry;
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, strong)NSString *startID;
@property (nonatomic, strong)NSString *stopID;
@property (nonatomic, strong)NSString *truckTypeID;
@property (nonatomic, strong)NSString *lengthStr;
@property (nonatomic, strong)NSString *baffle;
@property (nonatomic, strong)NSString *cargoTagID;
@property (nonatomic, assign)NSInteger tagType;
@property (nonatomic, assign)NSInteger TruckType;
@property (nonatomic, assign)NSInteger lenthType;
@property (nonatomic, assign)NSInteger baffType;

@end

@implementation SuppHallViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self requestSuppHallList];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 0;
    _startID = @"";
    _stopID = @"";
    _truckTypeID = @"";
    _lengthStr = @"";
    _baffle = @"";
    _cargoTagID = @"";
    _tagType = 0;
    _TruckType = 0;
    _lenthType = 0;
    _baffType = 0;
    _allHallAry = [NSMutableArray arrayWithCapacity:0];
    [self creatUI];
}

- (void)creatUI
{
    self.navigationItem.title = @"货源大厅";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = BacksColor;
    screeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45*displaywidth)];
    screeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:screeView];
    [self creatScreeView];
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 45*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-95*displaywidth-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-50*displaywidth, SCREEN_WIDTH, SCREER_HeiX+50*displaywidth)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 0, 50*displaywidth, 50*displaywidth) ImageName:@"sy_nav01" Target:self Action:@selector(backAction) Title:@"首页" Font:11.0];
    backBtn.backgroundColor = [UIColor clearColor];
    [backBtn setTitleColor:RGB(164, 164, 164) forState:UIControlStateNormal];
    [bottomView addSubview:backBtn];
    [backBtn setButtonContentCenter];
    
    UIButton *pushHallBtn = [ZCControl createButtonWithFrame:CGRectMake(70*displaywidth, 7.5*displaywidth, SCREEN_WIDTH-85*displaywidth, 35*displaywidth) ImageName:nil Target:self Action:@selector(pushHallAction) Title:@"我要发布..." Font:15.0];
    pushHallBtn.backgroundColor = RGB(221, 221, 221);
    [pushHallBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
    pushHallBtn.layer.cornerRadius = 4;
    pushHallBtn.layer.masksToBounds = YES;
    [bottomView addSubview:pushHallBtn];
    
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

//我要发布
- (void)pushHallAction
{
    UserAccountModel *userModel = [UserAccountModel shareMange];
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        [LTools showMBProgressWithText:@"请先登录" addToView:self.view];
        return;
    }
    if (userModel.isIdentify != 1)
    {
        [LTools showMBProgressWithText:@"请先实名认证" addToView:self.view];
        return;
    }
    ReleaseHallViewController *vc = [[ReleaseHallViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)creatScreeView
{
    NSArray *typeAry = @[@"发货地",@"收货地",@"信息筛选"];
    CGFloat W = SCREEN_WIDTH/typeAry.count;
    for (int i = 0; i < typeAry.count; i++)
    {
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth+W*i, 0, W-40*displaywidth, 45*displaywidth) Font:15.0 Text:typeAry[i] Color:RGB(53, 53, 53)];
        [screeView addSubview:nameLab];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(W-25*displaywidth+W*i, 17.5*displaywidth, 10*displaywidth, 10*displaywidth) ImageName:@"arrowicon"];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [screeView addSubview:imgView];
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(W*i, 0, W, 45*displaywidth) ImageName:nil Target:self Action:@selector(closeRoursAction:) Title:nil Font:12.0];
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 100+i;
        [screeView addSubview:btn];
        if (i == 0)
        {
            startLab = nameLab;
        }
        if (i == 1)
        {
            stopLab = nameLab;
        }
        if (i != 0)
        {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(W*i, 12.5*displaywidth, 1, 20*displaywidth)];
            lineView.backgroundColor = RGB(235, 235, 235);
            [screeView addSubview:lineView];
        }
        
    }
}

- (void)closeRoursAction:(UIButton *)btn
{
    NSInteger index = btn.tag-100;
    WEAKSELF;
    if (index != 2)
    {
        //发货地  //收货地
        CloseGoodsAddressViewController *vc = [[CloseGoodsAddressViewController alloc] init];
        vc.areaType = index;
        vc.isYJ = YES;
        vc.closeBlock = ^(NSString *name, NSInteger index)
        {
            NSArray *idAry = [name componentsSeparatedByString:@","];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (idAry.count == 2)
                {
                    if (index == 0)
                    {
                        _startID = idAry[1];
                        startLab.text = idAry[0];
                    }
                    else
                    {
                        _stopID = idAry[1];
                        stopLab.text = idAry[0];
                    }
                }
                [weakSelf loadNewHeaderData];
            });
        };
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    else
    {
        //信息筛选
        HallScreeningViewController *vc = [[HallScreeningViewController alloc] init];
        vc.tagType = _tagType;
        vc.TruckType = _TruckType;
        vc.lenthType = _lenthType;
        vc.baffType = _baffType;
        vc.closeBlock = ^(NSString *tagStr,NSString *truckId, NSString *lenthStr, NSString *baffStr,NSInteger tagid,NSInteger truck,NSInteger len,NSInteger baf)
        {
            weakSelf.truckTypeID = truckId;
            weakSelf.lengthStr = lenthStr;
            weakSelf.cargoTagID = tagStr;
            weakSelf.baffle = baffStr;
            weakSelf.tagType = tagid;
            weakSelf.TruckType = truck;
            weakSelf.lenthType = len;
            weakSelf.baffType = baf;
            [weakSelf loadNewHeaderData];
        };
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}

- (void)loadNewHeaderData
{
    _page = 0;
    [self requestSuppHallList];
    
}

- (void)loadMoreFootData
{
    _page ++;
    [self requestSuppHallList];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allHallAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = BacksColor;
    if (_allHallAry.count > 0)
    {
        HallModel *model = _allHallAry[indexPath.row];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"morenFace"];
        if (model.userheadImg.length > 0)
        {
            [imgView sd_setImageWithURL:[NSURL URLWithString:model.userheadImg] placeholderImage:[UIImage imageNamed:@"morenFace"]];
        }
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.layer.cornerRadius = 20*displaywidth;
        imgView.layer.masksToBounds = YES;
        [cell.contentView addSubview:imgView];
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(80*displaywidth, 15*displaywidth, SCREEN_WIDTH-160*displaywidth, 20*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"%@【%@】",model.username,model.cargoTagname] Color:BlaTitColor];
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@【%@】",model.username,model.cargoTagname]];
        NSRange titleRange = [[title string]rangeOfString:[NSString stringWithFormat:@"【%@】",model.cargoTagname]];
        [title addAttribute:NSForegroundColorAttributeName value:ThemeColor range:titleRange];
        nameLab.attributedText = title;
        [cell.contentView addSubview:nameLab];
        NSString *str = [self timeIntervalFromLastTime:model.createDtm lastTimeFormat:@"yyyy-MM-dd HH:mm:ss"];
        UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH- 80*displaywidth, 15*displaywidth, 65*displaywidth, 20*displaywidth) Font:12.0 Text:str Color:RGB(153, 153, 153)];
        timeLab.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:timeLab];
        UILabel *complaintLab = [ZCControl createLabelWithFrame:CGRectMake(0, 60*displaywidth, 70*displaywidth, 25*displaywidth) Font:10.0 Text:string(model.usercomplainCount, @"投诉") Color:RGB(153, 153, 153)];
        complaintLab.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:complaintLab];
        CGFloat W = SCREEN_WIDTH-85*displaywidth;
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(70*displaywidth, 35*displaywidth, W, 140*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        whiteView.layer.cornerRadius = 5*displaywidth;
        whiteView.layer.masksToBounds = YES;
        [cell.contentView addSubview:whiteView];
        UIImageView *sjImgView = [ZCControl createImageViewWithFrame:CGRectMake(55*displaywidth, 40*displaywidth, 20*displaywidth, 30*displaywidth) ImageName:@"sjx"];
        sjImgView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:sjImgView];
        UIImageView *startImgView = [ZCControl createImageViewWithFrame:CGRectMake(5*displaywidth, 10*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"congicon"];
        startImgView.contentMode = UIViewContentModeScaleAspectFit;
        [whiteView addSubview:startImgView];
        UILabel *startALab = [ZCControl createLabelWithFrame:CGRectMake(25*displaywidth, 5*displaywidth, W-30*displaywidth, 25*displaywidth) Font:15.0 Text:[NSString stringWithFormat:@"%@%@%@",model.shipmentcity,model.shipmentdistrict,model.shipmentname] Color:BlaTitColor];
        startALab.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
        [whiteView addSubview:startALab];
        
        UIImageView *stopImgView = [ZCControl createImageViewWithFrame:CGRectMake(5*displaywidth, 35*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"daoicon"];
        stopImgView.contentMode = UIViewContentModeScaleAspectFit;
        [whiteView addSubview:stopImgView];
        UILabel *stopALab = [ZCControl createLabelWithFrame:CGRectMake(25*displaywidth, 30*displaywidth, W-30*displaywidth, 25*displaywidth) Font:15.0 Text:[NSString stringWithFormat:@"%@%@%@",model.destinationCity,model.destinationDistrict,model.destinationname] Color:BlaTitColor];
        stopALab.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
        [whiteView addSubview:stopALab];
        NSString *volStr = model.cargoType;
        if (![model.weight isEqualToString:@""])
        {
            volStr = [volStr stringByAppendingString:[NSString stringWithFormat:@"/%@吨",model.weight]];
        }
        if (![model.volume isEqualToString:@""])
        {
            volStr = [volStr stringByAppendingString:[NSString stringWithFormat:@"/%@立方",model.volume]];
        }
        UILabel *volumeLab = [ZCControl createLabelWithFrame:CGRectMake(7.5*displaywidth, 55*displaywidth, W-15*displaywidth, 25*displaywidth) Font:13.0 Text:volStr Color:YellowColor];
        [whiteView addSubview:volumeLab];
        NSString *lenStr = @"不限长度";
        if (![model.length isEqualToString:@""])
        {
            lenStr = string(model.length, @"米");
        }
        if (![model.truckType isEqualToString:@""])
        {
            lenStr = [lenStr stringByAppendingString:[NSString stringWithFormat:@"/%@",model.truckType]];
        }
        if ([model.baffle integerValue] == 1)
        {
            lenStr = [lenStr stringByAppendingString:@"/需尾板"];
        }
        if ([model.baffle integerValue] == 0)
        {
            lenStr = [lenStr stringByAppendingString:@"/无需尾板"];
        }
        UILabel *lentnLab = [ZCControl createLabelWithFrame:CGRectMake(7.5*displaywidth, 80*displaywidth, W-15*displaywidth, 25*displaywidth) Font:13.0 Text:lenStr Color:ThemeColor];
        [whiteView addSubview:lentnLab];
        UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(7.5*displaywidth, 109*displaywidth, W-15*displaywidth, 1*displaywidth)];
        lineAview.backgroundColor = BacksColor;
        [whiteView addSubview:lineAview];
        UILabel *postLab = [ZCControl createLabelWithFrame:CGRectMake(7.5*displaywidth, 110*displaywidth, W-15*displaywidth, 30*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"发货时间：%@%@",model.shipmentDay,model.shipmentTime] Color:RGB(189, 189, 189)];
        [whiteView addSubview:postLab];
        UILabel *priceLab = [ZCControl createLabelWithFrame:CGRectMake(W-120*displaywidth, 110*displaywidth, 112.5*displaywidth, 30*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"￥%@元左右",model.price] Color:RGB(189, 189, 189)];
        priceLab.textAlignment = NSTextAlignmentRight;
        NSMutableAttributedString *title2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@元左右",model.price]];
        NSRange titleRange2 = [[title2 string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.price]];
        [title2 addAttribute:NSForegroundColorAttributeName value:YellowColor range:titleRange2];
        priceLab.attributedText = title2;
        [whiteView addSubview:priceLab];
        if ([model.ji integerValue] == 1)
        {
            UIImageView *jiImgView = [ZCControl createImageViewWithFrame:CGRectMake(W-25*displaywidth, 0, 25*displaywidth, 25*displaywidth) ImageName:@"lb_icon34"];
            [whiteView addSubview:jiImgView];
        }
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HallModel *model = _allHallAry[indexPath.row];
    DeliveryDetailsViewController *vc = [[DeliveryDetailsViewController alloc] init];
    vc.idstr = s_str(model.ID);
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180*displaywidth;
}

- (void)requestSuppHallList
{
    WEAKSELF;
    NSDictionary *dic = @{@"page":s_Integer(_page),
                          @"size":@"10",
                          @"baffle":_baffle,
                          @"cargoTag.id":_cargoTagID,
                           @"shipment.id":_startID,
                           @"destination.id":_stopID,
                           @"truckTypeId":_truckTypeID,
                           @"length":_lengthStr};
    [HYBaseHandler requestWithTheFormUrl:SERVER_cargoList Parmers:dic Success:^(id obj) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *hallAry = [HallModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_page == 0)
                {
                    [weakSelf.allHallAry removeAllObjects];
                }
                [weakSelf.allHallAry addObjectsFromArray:hallAry];
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lastTimeFormat:(NSString *)format1
{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    //    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    //    dateFormatter2.dateFormat = @"yyyy/MM/dd HH:mm:ss";
    //    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [self timeIntervalFromLastTime:lastDate ToCurrentTime:[NSDate date]];
    
}
- (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10)
    {
        return  @"刚刚";
    }
    else if (minutes < 60)
    {
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }
    else if (hours < 24)
    {
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30)
    {
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12)
    {
        return [NSString stringWithFormat: @"%ld月前",(long)month];
    }
    else if (yers >= 1){
        return [NSString stringWithFormat: @"%ld年前",(long)yers];
    }
    return @"";
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
